import Vue from 'vue'
import Router from 'vue-router'

import store from '../store/store'
import NProgress from 'nprogress' //引入进度条组件 yarn add nprogress
import 'nprogress/nprogress.css'

Vue.use(Router);

//路由懒加载
/**
 *@parma {String} name 文件夹名称
 *@parma {String} component 视图组件名称
 */
const getComponent = (name, component) => () => import(`@/views/${name}/${component}.vue`);

const myRouter = new Router({
    routes: [
        {
            path: '/',
            redirect: '/home',
            component: getComponent('login', 'index')
        },
        {
            path: '/login',
            name: 'login',
            component: getComponent('login', 'index')
        },
        {
            path: '/',
            component: getComponent('layout', 'layout'),
            children:[
                {
                    path: '/home',
                    name: 'home',
                    component: getComponent('home', 'home')
                },
            ]
        },
    ]
});


//判断是否存在token
myRouter.beforeEach((to, from, next) => {
    NProgress.start()
    if (to.path !== '/login' && !store.state.token) {
        //next('/login')
        NProgress.done() // 结束Progress
    } else {
        next();
    }
    if (to.meta.roles) {
        //to.meta.roles.includes(...store.getters.roles)?next():next('/404')
    } else {
        next();
    }
})

myRouter.afterEach(() => {
    NProgress.done() // 结束Progress
})
export default myRouter
